package timbap.visualizer.coreplugins;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import processing.core.PApplet;
import timbap.visualizer.api.model.RecordItem;
import timbap.visualizer.api.model.TimeCode;
import timbap.visualizer.api.plugin.container.AbstractTransitionModeController;

public class PlaybackCuedModeControlImpl extends AbstractTransitionModeController {

    private static final Log LOG = LogFactory.getLog(DefaultPlaybackModeControlImpl.class);

    private float rotation;

    @Override
    public void timeCodeUpdated(TimeCode pTimeCode) {
        super.timeCodeUpdated(pTimeCode);
        calcTurntableRotation();
        updateItems();
    }

    @Override
    public void keepAliveExpired() {
        // do nothing
    }

    private void calcTurntableRotation() {

        float tRotation = 0;
        if (getContext().getRecordItemManager().getRecordItemCount() > 0) {
            float tItemRotation = getTimeCode().getNormalizedAbsolutePosition()
                                  * getContext().getPlaylistManager().getPlaylistSize()
                                  / getContext().getRecordItemManager().getRecordItemCount();
            tRotation = (tItemRotation - (int)Math.floor(tItemRotation));
        }
        rotation = tRotation;
    }


    protected void updateItems() {

        RecordItem tSelectedRecordItem = getContext().getRecordItemManager().getSelectedRecordItem();

        tSelectedRecordItem.getTransformation().setXTranslation(0);
        tSelectedRecordItem.getTransformation().setYTranslation(0);
        tSelectedRecordItem.getTransformation().setScaleFactor(1);
        tSelectedRecordItem.getTransformation().setAlphaValue(1);

        tSelectedRecordItem.getTransformation().setRotation(PApplet.map(getRotation(),0,1,-PApplet.PI,PApplet.PI));
        tSelectedRecordItem.getTransformation().setXRotation(0);
        tSelectedRecordItem.setFractionPlayed(getTimeCode().getFractionPlayed());

    }


    public float getRotation() {
        return rotation;
    }

}